// pages/planDetailAdmin/index.ts

import {fontSizeCalc, handleCode, handleErrCode} from "../../utils/util";
import {adoptSubmit, adoptSubmitScore, getCuesSubmitDetails} from "../../service/api/api-cues-submit";
import {
    adoptAccountList,
    adoptInstructAccountPageList,
    adoptInstructAccountUpdate
} from "../../service/api/api-cues-active";

const rules = [{
    name: "score",
    rule: ["required", "isAmount", "range:[0.01,100]"],
    msg: ["积分不能为空", "请输入数字，保留两位小数", "范围0.01-100"]
}]

let appointUserIds = new Set();// 选中的用户id

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,// 上报id
        report: {},// 上报详情
        access: {} as any,// 当前用户权限
        currentUser: {},// 当前用户信息
        options: '',
        isAdmin: false,// 是否是管理员查看详情
        isShowScore: false,// 是否显示评分
        isShowAdopt: false,// 是否显示自己录用
        isShowManageAdopt: false,// 是否显示录用
        isShowAdoptContent: false,// 是否显示录用内容
        isShowAdoptCount: false,// 是否显示录用次数
        isShowAdoptCountClick: false,// 是否显示录用点击查看
        imgUrl: [],// 图片Url
        adoptRecordsList: [],// 录用记录列表
        adoptRecordsListBack: [],// 录用记录备份列表
        adoptInstructAccountList: [],// 可指派的用户列表
        adoptInstructAccountListBack: [],// 可指派的用户列表备份
        checkedAppointUserIds: [],// 编辑的时候默认选中
        galleryShow: false,// 是否显示图片预览

        drawerVisible: false,// 右侧抽屉是否显示
        drawerSecVisible: false,// 右侧第二抽屉是否显示


        modal: false,// 是否显示弹窗
        modalReward: '',// 弹窗输入的积分

        hasTips: false,// 是否已经提示过了

        currentTop: 0,// 上面收缩显示
        currentMid: 1,// 中间收缩显示
        currentBot: 0,// 下面收缩显示

        labelSize: fontSizeCalc(28),
        inputSize: fontSizeCalc(32),
        btnWidth: fontSizeCalc(320) + 'rpx',
        btnHeight: fontSizeCalc(60) + 'rpx',
        btnLineHeight: fontSizeCalc(36) + 'rpx',
        tagSize: fontSizeCalc(20) + 'rpx',

        searchText: "",// 搜索关键字
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const id = options.id || 0;
        const {globalData: {access, currentUser}} = getApp();
        this.setData({
            access,
            id,
            // isAdmin: options.isAdmin === 'true',
            isShowAdopt: access.线索上报x选题计划x配置x需求者 && access.线索上报x选题计划x选题列表x收录线索,
            isShowManageAdopt: access.线索上报x选题计划x配置x管理员,
            isShowAdoptContent: access.线索上报x选题计划x选题列表x收录线索,
            isShowAdoptCount: access.线索上报x选题计划x选题列表x收录线索,// 是否显示录用次数
            isShowAdoptCountClick: (access.线索上报x选题计划x配置x管理员 || access.线索上报x选题计划x配置x需求者) && access.线索上报x选题计划x选题列表x收录线索,// 是否显示录用点击查看
            isShowScore: access.线索上报x选题计划x配置x管理员 && access.线索上报x选题计划x选题列表x评分线索,
            currentUser,
            options: JSON.stringify(options)
        })
        this.getReportDetail(id);
    },

    /**
     * 通过id获取子任务列表
     * @param id
     * @param hiddenLoading
     */
    async getReportDetail(id, hiddenLoading = false) {
        let _that = this;
        !hiddenLoading && wx.showLoading({
            title: '查询中...'
        })
        // 执行搜索函数
        await getCuesSubmitDetails({
            id,
        }).then(async (response) => {
            let report = response.data || {};
            report.attachment = this.handleAttachmentType(report.articleAttachments || [], report)
            _that.setData({
                report
            })
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            !hiddenLoading && wx.hideLoading();
            // if (!_that.data.hasTips){
            //     wx.showToast({
            //         title: '长按支持复制文章内容',
            //         icon: "none",
            //         duration: 1500
            //     })
            //     _that.setData({
            //         hasTips: true
            //     })
            // }
        })
    },

    /**
     * 录用与不录用
     */
    async setReportAdoptFun(params) {
        let _that = this;
        // if (!_that.data.isAdmin) {
        //     return
        // }
        const {isSelfAdopt, id} = this.data.report;
        const tips = isSelfAdopt === 1 ? '取消录用' : '录用';
        wx.showLoading({
            title: tips + '中...'
        })
        // 执行搜索函数
        await adoptSubmit(params).then(async (response) => {
            handleCode(response, tips + '成功');
            setTimeout(() => {
                _that.getReportDetail(id);
            }, 500)
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            wx.hideLoading();
            _that.modalCancel();
        })
    },

    /**
     * 评分
     */
    async setReportScoreFun(params) {
        let _that = this;
        if (!_that.data.isShowScore) {
            return
        }
        wx.showLoading({
            title: '请稍候...'
        })
        // 执行搜索函数
        await adoptSubmitScore(params).then(async (response) => {
            handleCode(response, '评分成功');
            setTimeout(() => {
                _that.getReportDetail(params.id);
            }, 500)
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            wx.hideLoading();
            _that.modalCancel();
        })
    },

    /**
     * 获取录用列表
     */
    async getAdoptListFun() {
        let _that = this;
        const {id} = this.data.report;
        wx.showLoading({
            title: '查询中...'
        })
        // 执行搜索函数
        await adoptAccountList({
            articleId: id,
        }).then(async (response) => {
            _that.setData({
                adoptRecordsList: response.data || []
            })
            _that.showDrawer()
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 获取录用列表
     */
    async getAdoptInstructAccountListFun() {
        let _that = this;
        const {id} = this.data.report;
        wx.showLoading({
            title: '查询中...'
        })
        await adoptInstructAccountPageList({
            articleId: id,
            current: 1,
            pageSize: 100,
        }).then(async (response) => {
            _that.setData({
                adoptInstructAccountList: _that.readyList(response?.data?.data || [])
            })
            // 处理一下选中的问题
            _that.data.adoptInstructAccountList.forEach(item => {
                _that.getChildrenValue(item)
            })
            _that.showSecDrawer()
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 设置录用更新
     */
    async adoptInstructAccountUpdateFun() {
        let _that = this;
        const {id} = this.data.report;
        wx.showLoading({
            title: '保存中...'
        })
        await adoptInstructAccountUpdate({
            accounts: _that.data.checkedAppointUserIds,
            articleId: id,
            type: 1,// 类型区分 1:线索征集，2:主动报送
        }).then(async (response) => {
            handleCode(response, '保存成功');
            _that.closeSecDrawer();
            setTimeout(() => {
                _that.getAdoptListFun();
                _that.getReportDetail(id, true);
            }, 500)
        }).catch(error => {
            console.warn(error)
            handleErrCode()
        }).finally(() => {
            wx.hideLoading();
        })
    },


    /**
     * 处理一下附件内容
     * @param list
     * @param voucherType
     */
    handleAttachmentType(list = [], {isImage, isFile}) {
        return list.map(item => {
            let attachmentName = '';
            // if (isImage === 1) {
            let {content = ''} = item;
            const hashIndex = content?.indexOf('?');
            content = hashIndex !== -1 ? content?.substring(0, hashIndex) : content;
            attachmentName = decodeURI((content.split('/').pop() || '').replace(/[\?].*$/g, ''));
            // attachmentName = '某某图片11111某某图片11111某某图片11111某某图片11111某某图片11111某某图片11111.png';
            // }
            return {
                ...item,
                attachmentName
            }
        })
    },

    /**
     * 附件点击
     */
    attachmentItemClick(e: any) {
        const {attachment = []} = this.data.report || {};
        this.showGalleryFun(
            attachment.map(item => {
                return {
                    src: item.content,
                    desc: item.voucherName
                }
            }))
    },

    /**
     * 显示弹窗弹窗
     */
    showModal() {
        const report = this.data.report;
        this.setData({
            modal: true,
            modalReward: report.score ?? 0,
        })
    },

    /**
     * 关闭弹窗弹窗
     */
    modalCancel() {
        this.setData({
            modal: false,
            modalReward: '',
        })
    },

    /**
     * 收录确认弹窗
     */
    modalConfirmFun() {
        const {report, modalReward} = this.data || {}
        let formData = {
            score: modalReward
        };
        this.selectComponent("#form").validate(formData, rules).then(res => {
            this.setReportScoreFun({...formData, id: report.id || 0})
        }).catch(errors => {
            console.log(errors)
        })
    },

    /**
     * 收录确认弹窗
     */
    confirmFun() {
        const report = this.data.report || {};
        this.setReportAdoptFun({id: report.id || 0})
    },

    /**
     * 显示弹窗弹窗
     */
    showGalleryFun(imgUrl: any) {
        this.setData({
            galleryShow: true,
            imgUrl,
        })
    },

    /**
     * 关闭弹窗弹窗
     */
    hideGalleryFun() {
        this.setData({
            galleryShow: false,
            imgUrl: [],
        })
    },

    /**
     * 改变collapse
     * @param e
     */
    changeCollapse(e: any) {
        const curTag = e.currentTarget.dataset.item || '';
        this.setData({
            [curTag]: this.data[curTag] === 0 ? 1 : 0
        })
    },

    /**
     * 显示侧面抽屉
     */
    showDrawer() {
        this.setData({
            drawerVisible: true,
            adoptRecordsListBack: this.data.adoptRecordsList
        })
    },

    /**
     * 关闭抽屉
     */
    closeDrawer() {
        this.setData({
            drawerVisible: false,
            adoptRecordsList: [],
            adoptRecordsListBack: [],
        })
    },

    /**
     * 显示侧面抽屉
     */
    showSecDrawer() {
        this.setData({
            drawerSecVisible: true,
            adoptInstructAccountListBack: this.data.adoptInstructAccountList
        })
    },

    /**
     * 关闭抽屉
     */
    closeSecDrawer() {
        appointUserIds.clear();
        this.setData({
            drawerSecVisible: false,
            adoptInstructAccountList: [],
            adoptInstructAccountListBack: [],
        })
    },

    /**
     * 单位树节点 修改
     */
    adoptItemCheck(e: any) {
        let data = e.currentTarget.dataset.item || {};
        if (data.disabled) {// 禁用不可选
            return
        }
        let dataList = this.data.adoptInstructAccountList;
        const targetIndex = dataList.findIndex(item => item.accountId === data.accountId);// 找到下标
        data.checked = !data.checked;// 取反
        this.getChildrenValue(data);// 处理选中一下
        dataList[targetIndex] = data;// 替换一下
        this.setData({
            checkedAppointUserIds: Array.from(appointUserIds),
            adoptInstructAccountList: dataList,// 更新列表
        })
    },

    /**
     * 获取子类值
     */
    getChildrenValue({checked, accountId}) {
        if (accountId) {
            if (checked) {// 选中了，就都加进去
                appointUserIds.add(accountId);
            } else {// 没选中，找一下删掉
                appointUserIds.delete(accountId)
            }
        }
    },

            /**
     * 复制标题
     */
    copyName(e: any) {
      let text = e.currentTarget.dataset?.text || '';
      text = text.replace(/<[^>]*>/g, '');
      wx.setClipboardData({
          data: text ,
          success: function (res) {
              wx.showToast({
                  title: '复制标题成功',
                  icon: "none",
                  duration: 1500
              })
          }
      });
  },


    /**
     * 复制内容
     */
    copyContent(e: any) {
        let text = e.currentTarget.dataset?.text || '';
        text = text.replace(/<[^>]*>/g, '');
        const mpHtml = this.selectComponent('#mpHtml');
        wx.setClipboardData({
            data: mpHtml?.getText() || text,
            success: function (res) {
                wx.showToast({
                    title: '复制内容成功',
                    icon: "none",
                    duration: 1500
                })
            }
        });
    },

    /**
     * 开始搜索
     * @param detail
     */
    searchFun({detail = {value: ''}}) {
        const all = !detail.value;// 输入一些空值就去查全部
        this.setData({
            searchText: detail.value,
            adoptRecordsList: this.data.adoptRecordsListBack.filter(
                item => all || item?.accountName?.includes(detail.value)
            ),
        })
    },

    /**
     * 搜索取消
     */
    searchCancel() {
        this.setData({
            searchText: "",
            adoptRecordsList: this.data.adoptRecordsListBack
        })
    },

    /**
     * 预备Tree结构数据
     * @param data
     */
    readyList(data): any {
        let treeData = [];
        if (Array.isArray(data)) {
            treeData = data.map(item => {
                const {selected, disabled, isInstruct} = item;
                let newItem = {
                    checked: selected === 1,// 默认选中
                    disabled: disabled === 1,// 是否禁用
                    tagType: isInstruct === 1 ? 'warning' : 'green',// tag样式
                    tagText: isInstruct === 1 ? '指令' : '自主',// tag样式
                };
                // 禁用的话，那就要处理一下灰色
                if (newItem.disabled) {
                    newItem.tagType = 'gray'
                    newItem.tagText = '自主，不可选择'
                }
                return {...item, ...newItem}
            });
        }
        return treeData;
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    taskExecuteShareFun() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    }
})